// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-18 14:39
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.DateTrain;

/**
 * 简单银行交易系统的实现 -> 交易失败情况 -> 账户余额不足
 */
class Bank {
    long[] balance;

    /**
     * 银行账户初始化
     *
     * @param balance
     */
    public Bank(long[] balance) {
        this.balance = balance;
    }

    /**
     * 转账功能，实现从account1转账给account2
     *
     * @param account1
     * @param account2
     * @param money
     * @return
     */
    public boolean transfer(int account1, int account2, long money) {
        if (!(isExits(account1 - 1) && isExits(account2 - 1))) {
            // 当前账户不存在
            return false;
        }

        if (balance[account1 - 1] < money) {
            return false;
        } else {
            balance[account1 - 1] -= money;
            balance[account2 - 1] += money;
            return true;
        }
    }

    /**
     * 向指定账户存款
     *
     * @param account
     * @param money
     * @return
     */
    public boolean deposit(int account, long money) {
        if (!isExits(account - 1)) {
            return false;
        }
        balance[account - 1] += money;
        return true;
    }

    /**
     * 从指定账户中取款
     *
     * @param account
     * @param money
     * @return
     */
    public boolean withdraw(int account, long money) {
        if (!isExits(account - 1) || balance[account - 1] < money) {
            return false;
        }
        balance[account - 1] -= money;
        return true;
    }

    boolean isExits(int account) {
        if (account >= balance.length || account < 0) {
            return false;
        }
        return true;
    }
}